package com.ly.springsolrtest.springsolr.util;
import cn.hutool.core.util.ReflectUtil;
import com.ly.springsolrtest.springsolr.common.SolrParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * solr工具类。用来转换javabean和数据库管理
 *
 * @param
 * @author linweijian
 * @date 2018/4/2 9:48
 * @return
 */
public class SolrUtil {


    /**
     * 私有构造器,防止实例化
     */
    private SolrUtil(){}
    /**
     * 将SolrDocument 转换为Bean
     *
     * @param record
     * @param clazz
     * @return bean
     */
    private static Object toBean(SolrDocument record, Class clazz) {
        Object obj = null;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e1) {
            e1.printStackTrace();
        }
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Object value = record.get(field.getName());
            try {
                BeanUtils.setProperty(obj, field.getName(), value);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 根据文件名称获取文件类型
     *
     * @param filename
     * @return java.lang.String
     * @author linweijian
     * @date 2018/4/2 14:27
     */
    private static String getFileContentType(String filename) {
        String contentType;
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        if (prefix.equals("xlsx")) {
            contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        } else if (prefix.equals("pdf")) {
            contentType = "application/pdf";
        } else if (prefix.equals("doc")) {
            contentType = "application/msword";
        } else if (prefix.equals("txt")) {
            contentType = "text/plain";
        } else if (prefix.equals("xls")) {
            contentType = "application/vnd.ms-excel";
        } else if (prefix.equals("docx")) {
            contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (prefix.equals("ppt")) {
            contentType = "application/vnd.ms-powerpoint";
        } else if (prefix.equals("pptx")) {
            contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        } else {
            contentType = "othertype";
        }

        return contentType;
    }

    /**
     * 添加索引
     *
     * @param entities
     * @return void
     * @author linweijian
     * @date 2018/4/2 10:31
     */
    public static <T> void save(HttpSolrClient solrClient, T... entities) {
        for (T entity : entities) {
            try {
                solrClient.addBean(entity);
                solrClient.commit();
            } catch (IOException | SolrServerException e) {
                e.printStackTrace();
                try {
                    solrClient.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }
    }

    /**
     * 添加索引
     *
     * @param solrClient, solrInputDocument
     * @return void
     * @author linweijian
     * @date 2018/4/2 17:25
     */
    public static void save(HttpSolrClient solrClient, SolrInputDocument... solrInputDocument) {
        try {
            solrClient.add(Arrays.asList(solrInputDocument));
            solrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ID删除索引
     *
     * @param solrClient, id
     * @return void
     * @author linweijian
     * @date 2018/4/2 10:36
     */
    public static void deleteById(HttpSolrClient solrClient, String id) {
        try {
            solrClient.deleteById(id);
            solrClient.commit();
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
            try {
                solrClient.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }

    /**
     * 根据查询语句删除索引
     *
     * @param solrClient, query
     * @return void
     * @author linweijian
     * @date 2018/4/2 10:37
     */
    public static void deleteByQuery(HttpSolrClient solrClient, String query) {
        try {
            solrClient.deleteByQuery(query);
            solrClient.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ID查找索引
     *
     * @param solrClient, id, clazz
     * @return T
     * @author linweijian
     * @date 2018/4/2 10:43
     */
    public static <T> T queryById(HttpSolrClient solrClient, String id, Class<? extends T> clazz) {
        try {
            SolrDocument solrDocument = solrClient.getById(id);
            return (T) SolrUtil.toBean(solrDocument, clazz);
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 优化solr索引
     *
     * @param collection, solrClient
     * @return void
     * @author linweijian
     * @date 2018/4/2 10:45
     */
    public static void optimize(HttpSolrClient solrClient, String collection) {
        try {
            solrClient.optimize(collection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据查询的关键字返回高亮的结果
     *
     * @param solrClient, solrParams, startIndex, pageSize
     * @return java.util.List<T>
     * @author linweijian
     * @date 2018/4/2 11:08
     */
    public static <T> List<T> getHighlight(HttpSolrClient solrClient, SolrParams solrParams, int startIndex, int pageSize, Class<?> clazz) {
        SolrQuery solrQuery = new SolrQuery();
        if (StringUtils.isNotEmpty(solrParams.getQueryString())) {
            solrQuery.setQuery(solrParams.getQueryString()); // 设置查询关键字
        }
        solrQuery.setHighlight(solrParams.isEnableHighlight()); // 开启高亮
        solrQuery.setStart(startIndex * pageSize);
        solrQuery.setRows(pageSize);//分页
        if (StringUtils.isNotEmpty(solrParams.getWriterType())) {
            solrQuery.setParam("ws", solrParams.getWriterType());
        }
        if (solrParams.getHighlightField() != null && solrParams.getHighlightField().size() > 0) {
            for (String field : solrParams.getHighlightField()) {
                solrQuery.addHighlightField(field); // 高亮字段
            }
        }
        if (StringUtils.isNotEmpty(solrParams.getHighlightSimplePre())) {
            solrQuery.setHighlightSimplePre(solrParams.getHighlightSimplePre()); // 高亮单词的前缀
        }

        if (StringUtils.isNotEmpty(solrParams.getHighlightSimplePost())) {
            solrQuery.setHighlightSimplePost(solrParams.getHighlightSimplePost()); // 高亮单词的后缀
        }
        solrQuery.setHighlightFragsize(solrParams.getHighlightFragsize());
        QueryResponse response;
        List<T> list = new ArrayList<>();
        try {
            response = solrClient.query(solrQuery);
            //获取查询的结果
            SolrDocumentList documentList = response.getResults();
            //高亮的结果
            Map<String, Map<String, List<String>>> highLightResult = response.getHighlighting();
            //总记录数
            long count = documentList.getNumFound();
            for (SolrDocument document : documentList) {
                T obj = (T) SolrUtil.toBean(document, clazz);
                //获取高亮的字段
                if (solrParams.getHighlightField() != null && solrParams.getHighlightField().size() > 0) {
                    for (String field : solrParams.getHighlightField()) {
                        List<String> fieldList = highLightResult.get(document.get("id")).get(field);
                        if (fieldList != null && fieldList.size() > 0) {
                            ReflectUtil.setFieldValue(obj, field, fieldList.get(0));
                        }
                    }
                }
                list.add(obj);
            }

        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 添加文件索引
     * filePath格式:E:/solr.docx
     *
     * @param solrClient, filePath
     * @return void
     * @author linweijian
     * @date 2018/4/2 14:04
     */
    public static void saveFile(HttpSolrClient solrClient, String filePath) {
        ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/extract");
        try {
            File file = new File(filePath);
            String fileName = file.getName();
            String contentType = getFileContentType(filePath);
            up.addFile(file, contentType);
            up.setParam("literal.path", file.getPath());
            up.setParam("literal.id", fileName);
            up.setParam("literal.fileName", fileName);
            //up.setParam("uprefix", "attr_");
            up.setParam("fmap.content", "content");
            up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
            solrClient.request(up);
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
    }


}
